<?php
namespace app\service;

use app\common\model\UserModel;
use app\common\model\UserMsgModel;
use app\common\model\UflModel;
use app\common\model\UserGradeModel;
use app\common\utils\RedisUtils;

class User
{
    /**
     * User表
     *
     * @var [type]
     */
    public $u_model;

    /**
     * 邮件表
     *
     * @var [type]
     */
    public $um_model;

    /**
     * 订单表
     *
     * @var [type]
     */
    public $ufl_model;

    public function __construct()
    {
        $this->u_model = new UserModel();
        $this->um_model = new UserMsgModel();
        $this->ufl_model = new UflModel();
    }

    /**
     * 设置玩家在线状态
     */
    public function setOnline($uid, $cid)
    {
        $key = 'player_online_'.$uid;
        RedisUtils::setu($key, $cid);
    }

    /**
     * 获取玩家在线状态
     *
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function getOnline($uid)
    {
        $key = 'player_online_'.$uid;
        return RedisUtils::get($key);
    }

    /**
     * 移除玩家在线状态
     */
    public function rmOnline($uid)
    {
        $key = 'player_online_'.$uid;
        RedisUtils::rm($key);
    }

    /**
     * 获取用户余额
     *
     * @param  [type] $uid 用户id
     * @return [type]      [description]
     */
    public function getBalance($uid)
    {
        return $this->u_model->getFieldByUid($uid, 'balance');
    }

    /**
     * 获取用户名称
     *
     * @param  [type] $uid 用户id
     * @return [type]      [description]
     */
    public function getUsername($uid)
    {
        if (empty($uid)) return 0;
        return $this->u_model->getFieldByUid($uid, 'username');
    }

    /**
     * 获取用户名称
     *
     * @param  [type] $uid 用户id
     * @return [type]      [description]
     */
    public function getLoginUser($uid)
    {
        if (empty($uid)) return 0;
        return $this->u_model->getFieldByUid($uid, 'phone');
    }

    /**
     * 余额更新可为负数
     *
     * @param  [type] $uid    用户id
     * @param  [type] $amount 数目
     * @return [type]         [description]
     */
    public function updateBalance($uid, $amount)
    {
        return $this->u_model->where(['uid' => $uid])
            ->setInc('balance', $amount);
    }

    /**
     * 结算牌局
     *
     * @param  [type] $user   [description]
     * @param  [type] $maxUid [description]
     * @param  [type] $tid    [description]
     * @return [type]         [description]
     */
    public function settleMatch($user, $maxUid, $tid, $innings)
    {
        $totalAmount  = 0;
        $winBetAmount = 0; // 赢的人的投注金额
        foreach ($user as $k => $v) {
            $totalAmount += $v['bet_balance'];
            if ($v['uid'] == $maxUid) {
                $winBetAmount = $v['bet_balance'];
            }
        }

        // 判断可赢金额
        $canWinAmount = $winBetAmount*2;
        if ($canWinAmount >= $totalAmount) {
            // 不退其它人金额，直接全部赢走
            foreach ($user as $k => $v) {
                $insert = [
                    'uid' => $v['uid'],
                    'deal_type' => ORDER_TYPE_BETLOSE,
                    'deal_amount' => $v['bet_balance'],
                    'tid' => $tid,
                    'innings' => $innings
                ];
                $win = 0 - $v['bet_balance'];

                if ($v['uid'] == $maxUid) {
                    $insert['deal_type'] = ORDER_TYPE_BETWIN;
                    $insert['deal_amount'] = $canWinAmount;
                    $win = $canWinAmount;
                }
                $this->ufl_model->insertOrder($insert);
                $user[$k]['win'] = $win;
            }
        } else {
            // 退还部分人金额
            $useless = $totalAmount - $canWinAmount;
            $userCount = count($user) - 1;

            if ($userCount > 0) {
                $uselessAmount = (int)($useless / $userCount);
                foreach ($user as $k => $v) {
                    $insert = [
                        'uid' => $v['uid'],
                        'deal_type' => ORDER_TYPE_BETBACE,
                        'deal_amount' => $uselessAmount,
                        'bet_amount' => $v['bet_balance'],
                        'tid' => $tid,
                        'innings' => $innings
                    ];
                    $win = 0 - ($v['bet_balance'] - $uselessAmount);

                    if ($v['uid'] == $maxUid) {
                        $insert['deal_type'] = ORDER_TYPE_BETWIN;
                        $insert['deal_amount'] = $canWinAmount;
                        $win = $canWinAmount;
                    }
                    $this->ufl_model->insertOrder($insert);
                    $user[$k]['win'] = $win;
                }
            }
        }

        return $user;
    }

    /**
     * 给用户发送信息
     *
     * @param  [type] $uid [description]
     * @param  [type] $msg [description]
     * @return [type]      [description]
     */
    public function sendEmailToUid($uid, $msg)
    {
        $data = [
            'uid' => $uid,
            'msg' => $msg
        ];
        return $this->um_model->save($data);
    }

    /**
     * 获取全部战绩
     *
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function getUserScoreList($uid)
    {
        $ugModel = new UserGradeModel();
        $list = $ugModel
            ->where(['uid' => $uid])
            ->page(1, 50)
            ->order('create_time desc')
            ->all();

        return $list;
    }

    /**
     * 获取战绩详细
     *
     * @param  [type] $tid     [description]
     * @param  [type] $innings [description]
     * @return [type]          [description]
     */
    public function getScoreDetails($tid, $innings)
    {
        $ugModel = new UserGradeModel();
        $list = $ugModel
            ->where(['tid' => $tid, 'innings' => $innings])
            ->order('create_time desc')
            ->all();

        foreach ($list as $k => &$v) {
            $v['username'] = $this->u_model->getUserName($v['uid']);
            if ($v['win'] > 0) $v['win'] = '+'.$v['win'];
        }

        return $list;
    }

    /**
     * 获取用户邮件
     *
     * @param  [type] $uid 用户id
     * @return [type]      [description]
     */
    public function getUserMsgList($uid)
    {
        $list = $this->um_model
            ->where(['uid' => $uid])
            ->order('create_time desc')
            ->all();

        return $list;
    }

    /**
     * 获取未读邮件
     *
     * @param  [type] $uid 用户id
     * @return [type]      [description]
     */
    public function getUnreadMsg($uid)
    {
        $map = [
            'uid' => $uid,
            'is_unread' => 1
        ];

        return $this->um_model
            ->where($map)
            ->count();
    }

    /**
     * 删除用户邮件
     *
     * @param  [type] $uid [description]
     * @param  [type] $id  [description]
     * @return [type]      [description]
     */
    public function deletedUserEmail($uid, $id)
    {
        if ($id == 'all') {
            $this->um_model->where(['uid' => $uid])->delete();
        } else {
            $this->um_model->where(['id' => $id])->delete();
        }
    }

    /**
     * 已读用户邮件
     *
     * @param  [type] $uid [description]
     * @param  [type] $id  [description]
     * @return [type]      [description]
     */
    public function readUserEmail($uid, $id)
    {
        if ($id == 'all') {
            $this->um_model->where(['uid' => $uid])->update(['is_unread' => 0]);
        } else {
            $this->um_model->where(['id' => $id])->update(['is_unread' => 0]);
        }
    }

    /**
     * 创建6位数用户id
     *
     * @return [type] [description]
     */
    public function buildId()
    {
        $file_path = 'buildIds/ids.pid';

        if (!file_exists($file_path)) {
            $file = fopen($file_path, 'w');
            $txt = mt_rand(1, 3).mt_rand(10000, 99999);
            $data = [ 'count' => 0, 'id' => $txt ];
        } else {
            $txt = file_get_contents($file_path);
            $file = fopen($file_path, 'w');
            $data = json_decode($txt, true);
            $data['count']++;
        }

        fwrite($file, json_encode($data));
        fclose($file);

        return (int)$data['id'] + (int)$data['count'];
    }

    /**
     * 创建6位数高效id
     *
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function buildSixId($name)
    {
        $file_path = 'public/buildIds/'.$name.'.pid';

        if (!file_exists($file_path)) {
            $file = fopen($file_path, 'w');
            $txt = mt_rand(1, 3).mt_rand(10000, 99999);
            $data = [ 'count' => 0, 'id' => $txt ];
        } else {
            $txt = file_get_contents($file_path);
            $file = fopen($file_path, 'w');
            $data = json_decode($txt, true);
            $data['count']++;
        }

        fwrite($file, json_encode($data));
        fclose($file);

        return (int)$data['id'] + (int)$data['count'];
    }
}
